package com.caimiao.miao.page.master.system.lottery;

import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.caimiao.miao.R;
import com.caimiao.miao.interfaces.BaseActivity;
import com.caimiao.miao.library.usb.interfaces.IUsbReadCallback;
import com.caimiao.miao.library.usb.logic.UsbCode;
import com.caimiao.miao.library.usb.logic.UsbScheduler;
import com.caimiao.miao.library.usb.logic.UsbUtil;
import com.caimiao.miao.library.usb.accessory.Command;
import com.caimiao.miao.library.utils.DecimalUtil;

import java.util.ArrayList;

public class LotteryActivity extends BaseActivity implements View.OnClickListener {
    private ListView mListView;
    private CommandAdapter mAdapter;
    private EditText mEtCode, mEtNum1, mEtNum2;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_lottery;
    }

    @Override
    protected void initUI() {
        mListView = findViewById(R.id.mainLvTest);
        mEtCode = findViewById(R.id.mainEtCode);
        mEtNum1 = findViewById(R.id.mainEtNum1);
        mEtNum2 = findViewById(R.id.mainEtNum2);
    }

    @Override
    protected void initLogic() {
        findViewById(R.id.mainBtnSend).setOnClickListener(this::onClick);
        UsbUtil.getInstance().initUsbControl(this);
        UsbUtil.getInstance().addUsbReadCallback(new IUsbReadCallback() {
            @Override
            public void call(Command command) {
                if (command.getStatus() != UsbCode.SCHEDULER_STATUS_TIMEOUT
                        && command.getCommand() == null) return;

                if (mAdapter == null) {
                    mAdapter = new CommandAdapter(getActivity(), new ArrayList<>());
                    mAdapter.addCommand(command);
                    mListView.setAdapter(mAdapter);
                } else {
                    mAdapter.addCommand(command);
                }
            }
        });
    }

    private UsbScheduler mUsbLooper;

    @Override
    protected void onResume() {
        super.onResume();
        UsbUtil.getInstance().resumeAccessory();
    }

    @Override
    protected void onDestroy() {
        UsbUtil.getInstance().destroy();
        super.onDestroy();
        mUsbLooper.close();
        mUsbLooper = null;
    }

    @Override
    public void onClick(View v) {
        int code = DecimalUtil.getInteger(mEtCode.getText().toString());
        int num1 = DecimalUtil.getInteger(mEtNum1.getText().toString());
        int num2 = DecimalUtil.getInteger(mEtNum2.getText().toString());
        UsbUtil.getInstance().addCommand(code, num1, num2);
    }
}
